//
//  TBCPlayerViewController.m
//  待定
//
//  Created by EricXie on 15/11/9.
//  Copyright © 2015年 BoyaLee. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "TBCPlayerViewController.h"
#import "TBCRadioListModel.h"
#import "UIImage+TBCBlur.h"

@interface TBCPlayerViewController ()

@property (nonatomic, strong) UIImageView *bgImageV;

@property (nonatomic, strong) UIImageView *revolveImageV;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UISlider *slider;

@property (nonatomic, strong) CABasicAnimation *basicAnimation;

@property (nonatomic, strong) UIButton *beforeBtn;

@property (nonatomic, strong) UIButton *playBtn;

@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, copy) NSString *musicUrl;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UILabel *timeLabel;

@end

@implementation TBCPlayerViewController

//- (void)viewDidDisappear:(BOOL)animated
//{
//    [super viewDidDisappear:animated];
//    [self animationPause];
//}

- (void)viewWillAppear:(BOOL)animated
{
//    [super viewWillAppear:animated];
    // 判断是否是同一首歌的路径如果是,不做任何变化,继续播放如果不是,切歌
    if (![self.musicUrl isEqualToString:_radio.musicUrl]) {
        [_player stop];
        [_timer invalidate];
        [self creat];
        [self playMusic];
        _slider.value = 0;
        _timeLabel.text = @"00:00 / 00:00";
        [_playBtn setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        self.navigationController.navigationBar.alpha = 0;
        
        return;
    }
    
    [self creat];
    self.navigationController.navigationBar.alpha = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    [session setActive:YES error:nil];
    
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    self.player = [[STKAudioPlayer alloc] init];
    self.player.volume = 0.5;
    [self creatView];
    [self creat];
    
    UIImage *image = [UIImage imageNamed:@"fanhui.png"];
    //取消渲染
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(leftBarAction:)];
    
    
}


//自定义左侧按钮
-(void)leftBarAction:(UIBarButtonItem *)barItem
{
    [self.navigationController popViewControllerAnimated:YES];
}

+ (instancetype)shareRadioPlayerViewController
{
    static TBCPlayerViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[TBCPlayerViewController alloc] init];
    });
    
    return player;
}

// 铺界面思密达
- (void)creatView
{
    self.bgImageV = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_bgImageV addGestureRecognizer:tap];
    _bgImageV.userInteractionEnabled = YES;
    [self.view addSubview:_bgImageV];
    
    self.revolveImageV = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 0.1, HEIGHT * 0.1, WIDTH * 0.8, WIDTH * 0.8)];
    [self.view addSubview:_revolveImageV];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH * 0.5 - WIDTH * 0.4, HEIGHT * 0.55, WIDTH * 0.8, HEIGHT * 0.1)];
    _titleLabel.font = [UIFont systemFontOfSize:20];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_titleLabel];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(WIDTH * 0.2, HEIGHT * 0.65, WIDTH * 0.6, HEIGHT * 0.05)];
    [_slider addTarget:self action:@selector(progress:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_slider];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH * 0.3, HEIGHT * 0.65, WIDTH * 0.4, HEIGHT * 0.2)];
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_timeLabel];
    
    self.beforeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _beforeBtn.frame = CGRectMake(_slider.frame.origin.x, _slider.frame.origin.y + HEIGHT * 0.15, WIDTH * 0.1, WIDTH * 0.1);
    [_beforeBtn setBackgroundImage:[UIImage imageNamed:@"before"] forState:UIControlStateNormal];
    [_beforeBtn addTarget:self action:@selector(beforeBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_beforeBtn];
    _beforeBtn.layer.masksToBounds = YES;
    _beforeBtn.layer.cornerRadius = WIDTH * 0.05;
    
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _playBtn.frame = CGRectMake(WIDTH * 0.45, _beforeBtn.frame.origin.y, WIDTH * 0.1, WIDTH * 0.1);
    [_playBtn setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
    [_playBtn addTarget:self action:@selector(playBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playBtn];
    _playBtn.layer.masksToBounds = YES;
    _playBtn.layer.cornerRadius = WIDTH * 0.05;
    
    self.nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextBtn.frame = CGRectMake(_slider.frame.origin.x + _slider.frame.size.width - WIDTH * 0.1, _beforeBtn.frame.origin.y, WIDTH * 0.1, WIDTH * 0.1);
    [_nextBtn setBackgroundImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(nextBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextBtn];
    _nextBtn.layer.masksToBounds = YES;
    _nextBtn.layer.cornerRadius = WIDTH * 0.05;
}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    
    
    self.navigationController.navigationBar.alpha = 1.0;
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        [UIView animateWithDuration:2.0f animations:^{
            self.navigationController.navigationBar.alpha = 0;
        }];
        
    });
}

- (void)beforeBtnClicked
{
    self.indexPath--;
    if (-1 == _indexPath) {
        self.indexPath = _allMusicArray.count - 1;
    }
    [self creat];
    [self playMusic];
}

- (void)playBtnClicked
{
    if (STKAudioPlayerStatePaused == _player.state) {
        [_player resume];
        [self animationPause];
    } else if (STKAudioPlayerStatePlaying == _player.state)
    {
        [_player pause];
        [self animationReStart];
    }
//    else {
//        [self playMusic];
//    }
}

- (void)playMusic
{
    if (0 != _allMusicArray.count) {
        TBCRadioListModel *radio = [_allMusicArray objectAtIndex:_indexPath];
        self.radio = radio;
        self.musicUrl = _radio.musicUrl;
    } else {
        self.musicUrl = _musicUrl;
    }
    
    [_player play:_musicUrl];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(track) userInfo:nil repeats:YES];
}

- (void)track
{
    if (STKAudioPlayerStatePaused == _player.state) {
        [_playBtn setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    } else if (STKAudioPlayerStatePlaying == _player.state)
    {
        [_playBtn setImage:[UIImage imageNamed:@"suspend"] forState:UIControlStateNormal];
    }
    
    _slider.maximumValue = _player.duration;
    _slider.value = _player.progress;
    
    // 当前播放进度
    NSInteger proMin = (NSInteger)_player.progress / 60;
    NSInteger proSec = (NSInteger)_player.progress % 60;
    // duration总时长
    NSInteger durMin = (NSInteger)_player.duration / 60;
    NSInteger durSec = (NSInteger)_player.duration % 60;
    
    _timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    
    // 自动播放下一首
    if ((0.6 > _player.duration - _player.progress) && (_player.duration != _player.progress))
    {
        [self nextBtnClicked];
    }
    
}

- (void)nextBtnClicked
{
    _indexPath++;
    if (_indexPath == _allMusicArray.count) {
        self.indexPath = 0;
    }
    [self creat];
    [self playMusic];
}

- (void)creat
{
    TBCRadioListModel *radio = [[TBCRadioListModel alloc] init];
    if (_allMusicArray.count != 0) {
        radio = [_allMusicArray objectAtIndex:_indexPath];
    }
    
    self.imgUrl = radio.coverimg;
    _titleLabel.text = radio.title;
    
    // 转圈动画
    [_bgImageV sd_setImageWithURL:[NSURL URLWithString:_imgUrl]];
    _bgImageV.image = [_bgImageV.image boxblurImageWithBlur:0.7];
    _bgImageV.alpha = 0.6;
    
    [_revolveImageV sd_setImageWithURL:[NSURL URLWithString:_imgUrl]];
    _revolveImageV.layer.masksToBounds = YES;
    _revolveImageV.layer.cornerRadius = WIDTH * 0.8 / 2;
    _revolveImageV.layer.borderColor = [UIColor grayColor].CGColor;
    _revolveImageV.layer.borderWidth = 5;
    _revolveImageV.userInteractionEnabled = YES;
    
    [self revolveAnimate];
}

- (void)progress:(UISlider *)slider
{
    if (_player) {
        [_player seekToTime:slider.value];
    }
}

- (void)revolveAnimate
{
    self.basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    _basicAnimation.duration = 20;
    _basicAnimation.fromValue = [NSNumber numberWithInt:0];
    _basicAnimation.toValue = [NSNumber numberWithInt:M_PI * 2];
    [_basicAnimation setRepeatCount:NSIntegerMax];
    [_basicAnimation setAutoreverses:NO];
    [_basicAnimation setCumulative:YES];
    [_revolveImageV.layer addAnimation:_basicAnimation forKey:@"basicAnimation"];
}

- (void)animationPause
{
    CFTimeInterval stopTime = [_revolveImageV.layer timeOffset];
    // 初始化开始时间
    _revolveImageV.layer.beginTime = 0;
    // 初始化时间偏移量
    _revolveImageV.layer.timeOffset = 0;
    // 设置动画速度
    _revolveImageV.layer.speed = 1.0;
    // 计算时间差
    CFTimeInterval tempTime = [_revolveImageV.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
    // 重置设置动画开始时间
    _revolveImageV.layer.beginTime = tempTime;
}

- (void)animationReStart
{
    CFTimeInterval stopTime = [_revolveImageV.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    
    _revolveImageV.layer.speed = 0;
    
    _revolveImageV.layer.timeOffset = stopTime;
}

@end
